<%@page import="cn.kgcnews.service.impl.NewsServiceImpl"%>
<%@page import="cn.kgcnews.service.NewsService"%>
<%@page import="cn.kgcnews.utils.StringUtils"%>
<%@page import="java.io.File"%>
<%@page import="cn.kgcnews.pojo.NewsDetail"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	boolean isOK = false; //图片上传是否成功
	boolean isOnlyText = false; //是否为文字新闻
	String uploadPath = request.getServletContext().getRealPath("/")
			+ File.separator + "upload";
	// 如果目录不存在则创建
	File uploadDir = new File(uploadPath);
	if (!uploadDir.exists()) {
		uploadDir.mkdir();
	}
	NewsDetail news = new NewsDetail();
	//1:判断表单提交的内容形式
	boolean isMultipart = ServletFileUpload.isMultipartContent(request);
	if (isMultipart) {
		//2:创建文件上传所需的API实例
		FileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(factory);
		//3:解析request请求，获取FileItem对象集合
		List<FileItem> list = upload.parseRequest(request);
		//4:循环遍历集合中的数据
		for (FileItem item : list) {
			if (item.isFormField()) {
				//对象为普通表单
				String fieldName = item.getFieldName();
				if ("ntitle".equals(fieldName)) {
					news.setTitle(item.getString("UTF-8"));
				} else if ("nsummary".equals(fieldName)) {
					news.setSummary(item.getString("UTF-8"));
				} else if ("ntid".equals(fieldName)) {
					news.settId(Integer.valueOf(item.getString("UTF-8")));
				} else if ("nauthor".equals(fieldName)) {
					news.setAuthor(item.getString("UTF-8"));
				} else if ("ncontent".equals(fieldName)) {
					news.setContent(item.getString("UTF-8"));
				}
			} else {
				//对象为文件表单
				String name = item.getName();
				if (name != null && !"".equals(name)) {
					//控制文件的上传的类型
					if (!StringUtils.checkImg(name)) {
						out.println("<script>alert('新闻图片的格式不正确，请重新选择');history.back();</script>");
					} else {
						String fileName = StringUtils.getNewName(name);
						news.setPicPath(fileName);
						//远程服务器的文件地址
						File file = new File(uploadPath, fileName);
						item.write(file);
						isOK = true;
					}
				} else {
					isOnlyText = true;
				}

			}

		}
	}
	if (isOnlyText || isOK)

	{
		//调用业务逻辑层
		NewsService newsService = new NewsServiceImpl();
		news.setCreateDate(new Date());
		boolean result = newsService.publishNews(news);

		if (result) {
			//发布成功
			out.println("<script>alert('恭喜您，新闻发布成功');location.href='newslist.jsp';</script>");
			//发布失败
		} else {
			out.println("<script>alert('发布失败');history.back();</script>");
		}
	}
%>